package com.liqi.quartz.task;

import com.alibaba.fastjson.JSON;
import com.liqi.common.annotation.Log;
import com.liqi.sms.domain.MessageForWarn;
import com.liqi.sms.domain.SysShortMessage;
import com.liqi.sms.service.ISendMessageService;
import com.liqi.sms.service.ISysShortMessageService;
import com.liqi.sms.service.impl.SendMessageServiceImpl;
import com.liqi.sms.utils.PlatformConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component("shortMessageTask")
public class ShortMessageTask {

    @Autowired
    private ISendMessageService sendMessageService;

    @Autowired
    private ISysShortMessageService sysShortMessageService;
    @Autowired
    PlatformConfig platformConfig;
    private final static Logger logger = LoggerFactory.getLogger(ShortMessageTask.class);

    public void sendShortMessage() {

        List<SysShortMessage> messageList = sysShortMessageService.selectSysShortMessageBySendFlag("0");

        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = sdf.format(now) + " 00:00:00";
        String endTime = sdf.format(now) + " 23:59:59";

        if (messageList.size() == 0) {
            System.out.println("暂无需要发送的短信");
            logger.info("暂无需要发送的短信");
        } else {
            for (int i = 0; i < messageList.size(); i++) {
                List<SysShortMessage> sysShortMessages = sysShortMessageService.selectSysShortMessageByTime(startTime, endTime);

                    List<HashMap> getHashMaps = new ArrayList<>();
                    for (SysShortMessage message : sysShortMessages) {
                        HashMap map = JSON.parseObject(message.getTemplateParam(), HashMap.class);
                        getHashMaps.add(map);
                    }
                    Map<Object, Long> deviceIdMap = getHashMaps.stream().collect(
                            Collectors.groupingBy(doc -> doc.get("deviceId"), Collectors.counting()));

                    HashMap map = JSON.parseObject(messageList.get(i).getTemplateParam(), HashMap.class);
                    String deviceId = map.get("deviceId").toString();

                    Long shortMessageLimit = Long.valueOf(platformConfig.getShortMessageLimit());
                Long deviceIdLong = deviceIdMap.get(deviceId);
                if(sysShortMessages.size() == 0 || deviceIdLong==null) {
                    deviceIdLong=0L;
                }
                if (shortMessageLimit > deviceIdLong) {

                    try {

                        MessageForWarn messageForWarn = new MessageForWarn();
                        messageForWarn.setOperationPhoneNum(messageList.get(i).getPhoneNumbers());
                        messageForWarn.setOperationUserName(map.get("operationUserName").toString());
                        messageForWarn.setDeploymentAddress(map.get("deploymentAddress").toString());
                        messageForWarn.setDeploymentName(map.get("deploymentName").toString());

                        messageForWarn.setDeviceId(map.get("deviceId").toString());


                        messageForWarn.setErrorMessage(map.get("errorMessage").toString());


                        messageForWarn.setErrorTime(map.get("nowTime").toString());
                        messageForWarn.setReportedType(map.get("reportType").toString());

                        sendMessageService.sendMessage(messageForWarn);
                        messageList.get(i).setSendFlag("3");
                        messageList.get(i).setUpdateTime(new java.sql.Date(new java.util.Date().getTime()));
                        messageList.get(i).setUpdateBy("短信定时任务发送成功");
                        sysShortMessageService.updateSysShortMessage(messageList.get(i));
                    } catch (Exception e) {
                        messageList.get(i).setSendFlag("6");
                        messageList.get(i).setUpdateTime(new java.sql.Date(new java.util.Date().getTime()));
                        messageList.get(i).setUpdateBy("短信定时任务发送失败");
                        sysShortMessageService.updateSysShortMessage(messageList.get(i));
                        e.printStackTrace();
                    }
                } else {
                    messageList.get(i).setSendFlag("6");
                    messageList.get(i).setUpdateTime(new java.sql.Date(new java.util.Date().getTime()));
                    sysShortMessageService.updateSysShortMessage(messageList.get(i));
                    System.out.println("设备ID:" + deviceId + "已经达到今日短信发送上线");
                    logger.info("设备ID:" + deviceId + "已经达到今日短信发送上线");
                }
            }
        }
    }
}
